/*
   Copyright 2016 小新de蜡笔

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include "mygetline.h"

#define DEFSIZE 128

ssize_t mygetline (int fd, char **line)
{
	int i = 0, err = 0;
	char ch = 0;
	size_t size = DEFSIZE;
	char *tmp = NULL;

	if (NULL == *line) {
		*line = malloc(size);
		if (!*line) {
			return -ENOMEM;
		}
	}
	memset(*line, 0, size);

	for (i = 0; ; i++) {
		err = read(fd, &ch, 1);
		if (!err) { // EOF
			break;
		} else if (err < 0) { // ERROR
			return -errno;
		}

		if (i == (size - 2)) {
			/* 
			 * realloc(3): 
			 * If the new size is larger than the old size, 
			 * the added memory will not be initialized.
			 */
			size *= 2;
			tmp = malloc(size);
			if (!tmp) {
				return -ENOMEM;
			}
			memset(tmp, 0, size);
			memcpy(tmp, *line, size / 2);
			free(*line);
			*line = tmp;
			tmp = NULL;
		}

		//*((*line)++) = ch;
		(*line)[i] = ch;
		if ('\n' == ch) { // Line end
			(*line)[++i] = '\0';
			break;
		}
	}

	return i;

}

void mygetline_destroy (char **line)
{
	free(*line);
	*line = NULL;
}

